package com.mgkj.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mgkj.base.HttpResult;
import com.mgkj.common.result.Result;
import com.mgkj.common.utils.HttpClientUtil;
import com.mgkj.common.utils.TimeUtils;
import com.mgkj.common.utils.yf.InitMoneyUtils;
import com.mgkj.dto.*;

import com.mgkj.dto.MOCTGDto;
import com.mgkj.dto.yf.*;
import com.mgkj.entity.yf.*;
import com.mgkj.entity.*;
import com.mgkj.mapper.*;
import com.mgkj.service.CommonService;
import com.mgkj.service.EnterStorageService;
import com.mgkj.vo.NeedArrivalInsVo;

import com.mgkj.vo.yf.InitRaxVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static java.time.format.DateTimeFormatter.ofPattern;

/**
 * @author : ssy
 * @date: 2024-02-27
 * @Description:
 */
@Service
@Slf4j
public class EnterStorageServiceImpl implements EnterStorageService {

    @Resource
    private EnterStorageMapper enterStorageMapper;

    @Resource
    private CommonMapper commonMapper;

    @Resource
    private PURMAMapper purmaMapper;

    @Resource
    private PURTGMapper purtgMapper;


    @Resource
    private PURTHMapper purthMapper;

    @Resource
    private PURTCDMapper purtcdMapper;

    @Resource
    private WmsInvmlMapper wmsInvmlMapper;

    @Resource
    private WmsInvlaMapper wmsInvlaMapper;

    @Resource
    private DscmbMapper dscmbMapper;

    @Resource
    private CommonService commonService;

    @Resource
    private InvmbMapper invmbMapper;

    @Resource
    private InitPurtiMapper initPurtiMapper;

    @Resource
    private InitPurtjMapper initPurtjMapper;

    @Resource
    private InitPurtdMapper initPurtdMapper;
    @Resource
    private InvtaMapper invtaMapper;
    @Resource
    private InvtbMapper invtbMapper;


    @Override
    public Result insertjhd(JhdDto jhdDto) throws UnknownHostException {
        Map<String, String> map = new HashMap<>();
        int i = 1;
        Double jhje = 0.0;
        Double kkje = 0.0;
        Double zjs = 0.0;
        Double zyssl = 0.0;
        Double bbdkje = 0.0;
        Double bbse = 0.0;
        Double zysbzsl = 0.0;
        Double jhsl = 0.0;
        Double jhbzsl = 0.0;

        Purtg purtg = new Purtg();

        Map<String, Object> list = new HashMap<>();
        purtg.setTg001("3410");
        Long dh = commonMapper.getDH("PURTG", "TG002");

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter create_date = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

        // 格式化时间
        String formattedTime = currentTime.format(formatter1);
        String yyyyMMdd = currentTime.format(formatter1);

        Long time = Long.parseLong(formattedTime + "001");
        if (dh == null || dh < time) {
            dh = time;
        } else {
            dh++;
        }

        purtg.setTg002("" + dh);
        String company = commonMapper.getCompany();
        String creator = jhdDto.getCreator();
        String usrGroup = commonMapper.getUsrGroup(jhdDto.getCreator());
        String createDate = currentTime.format(create_date);
//        税率
        String ma064 = enterStorageMapper.getSL(jhdDto.getWorkCenter());
        purtg.setCompany(company);
        purtg.setCreator(creator);
        purtg.setUsrGroup(usrGroup);
        purtg.setCreateDate(createDate);
        purtg.setFlag("1");
        purtg.setTg003(yyyyMMdd);

        //工厂只有一个，先写死了
        purtg.setTg004("1000");
        purtg.setTg005(jhdDto.getWorkCenter());
        purtg.setTg006(jhdDto.getWorkCenterNo());

        LambdaQueryWrapper<PURMA> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PURMA::getMA001, jhdDto.getWorkCenter());
//        获取供应商基本信息
        PURMA purma = purmaMapper.selectOne(wrapper);
        purtg.setTg007(purma.getMA021());

        if (purma.getMA021().trim().equals("RMB")) {
            purtg.setTg008(1.0000000);
        } else {
//            获取币种汇率
            Map<String, Object> hl = purtgMapper.selectHL(purma.getMA021());
            purtg.setTg008((Double) hl.get("ME004"));
        }
        purtg.setTg009(purma.getMA030());
        purtg.setTg010(purma.getMA044());
        purtg.setTg012(0.0);
        purtg.setTg013("N");

        purtg.setTg014(yyyyMMdd);
        purtg.setTg015("N");
        purtg.setTg016(jhdDto.getTG016());

        List<Purth> purths = new ArrayList<>();
        List<PURTHDto> purthDtoList = jhdDto.getPurthDtoList();


        String modifier = purtg.getModifier();
        String modiDate = purtg.getModiDate();
        ArrayList<WmsInvml> wmsInvmls = new ArrayList<>();
        ArrayList<WmsInvla> wmsInvlas = new ArrayList<>();
        for (PURTHDto purthDto : purthDtoList) {
            //        额外要插入的两表
            WmsInvml wmsInvml = new WmsInvml();
            WmsInvla wmsInvla = new WmsInvla();

            wmsInvml.setCompany(company);
            wmsInvml.setCreator(creator);
            wmsInvml.setUsrGroup(usrGroup);
            wmsInvml.setCreateDate(createDate);
            wmsInvml.setModifier(modifier);
            wmsInvml.setModiDate(modiDate);
            wmsInvml.setFlag(1.0);
            wmsInvla.setCompany(company);
            wmsInvla.setCreator(creator);
            wmsInvla.setUsrGroup(usrGroup);
            wmsInvla.setCreateDate(createDate);
            wmsInvla.setModifier(modifier);
            wmsInvla.setModiDate(modiDate);
            wmsInvla.setFlag(1.0);

            Purth purth = new Purth();
            String xuh = String.format("%04d", i++);
            String workCenter = "%" + jhdDto.getWorkCenter() + "%";
            String factory;

            if (purthDto.getFactory() == null || purthDto.getFactory().isEmpty()) {
                factory = "1000";
            } else {
                factory = "%" + purthDto.getFactory() + "%";
            }

            list = enterStorageMapper.selectQMSTA(workCenter, purthDto.getDhjydb(), purthDto.getDhjydh(), purthDto.getXh(), purthDto.getJypc(), factory);
            purth.setCompany(company);
            purth.setCreator(creator);
            purth.setUsrGroup(usrGroup);
            purth.setCreateDate(createDate);
            purth.setFlag("1");
            purth.setTh001("3410");
            purth.setTh002("" + dh);
            purth.setTh003(xuh);
            purth.setTh004((String) list.get("CD004"));
            purth.setTh005((String) list.get("CD005"));
            purth.setTh006((String) list.get("CD006"));
            BigDecimal bigDecimal = (BigDecimal) list.get("CD013");
            purth.setTh007(purthDto.getJysl());
            jhsl += bigDecimal.doubleValue();
            purth.setTh008((String) list.get("CD007"));
            purth.setTh009((String) list.get("CD016"));
            //TODO 批号要抓
            //查出这个品号有没有开启批号管理
            int mb = commonMapper.getBooleanBatch(purth.getTh004());
            String jyph = purthDto.getJyph();
            if (jyph != null && !jyph.isEmpty() && mb != 0) {
                purth.setTh010(jyph);
            } else {
                purth.setTh010(formattedTime);
            }
//            purth.setTh010("********************");
            purth.setTh011((String) list.get("CD010"));
            purth.setTh012((String) list.get("CD011"));
            purth.setTh013((String) list.get("CD012"));
            String td021 = enterStorageMapper.selectvv((String) list.get("CD010"), (String) list.get("CD011"), (String) list.get("CD012"));
            purth.setUdf01(td021); //订单号
            purth.setTh014(yyyyMMdd);
            purth.setTh015(purthDto.getJysl());
            zyssl += purthDto.getJysl();
            Boolean isSame = purthMapper.isSameUnit(((String) list.get("CD004")).trim());
            if (isSame) {
                purth.setTh016(purthDto.getJysl());
            } else {
                Double calculate = purthMapper.calculate(purthDto.getJysl(), (String) list.get("CD004"));
                purth.setTh016(calculate);
            }
            BigDecimal TA008 = (BigDecimal) list.get("TA008");
            purth.setTh017(TA008.doubleValue());
            // 这里出问题就是，CD010\CD011\CD012是采购单别、单号、序号；查list的时候中没有这个值，应该是没采购单了
            Double DJ = purtcdMapper.selectOne((String) list.get("CD010"), (String) list.get("CD011"), (String) list.get("CD012"));
            if (DJ == null) {
                return Result.fail("没有找到对应采购单数据").message("没有找到对应采购单数据");
            }
            purth.setTh018(DJ);
            purth.setTh019(DJ * purthDto.getJysl());
            jhje += DJ * purthDto.getJysl();
            purth.setTh020(DJ * TA008.doubleValue());
            kkje = DJ * TA008.doubleValue();
            purth.setTh024(0.00);
            purth.setTh026("N");
            Boolean CQ = purtcdMapper.selectCQ((String) list.get("CD010"), (String) list.get("CD011"), (String) list.get("CD012"));
            if (CQ) {
                purth.setTh027("Y");
            } else {
                purth.setTh027("N");
            }
            purth.setTh028("2");
            purth.setTh029("N");
            purth.setTh030("N");
            purth.setTh031("N");
            purth.setTh032("N");
            purth.setTh033(purthDto.getBz());
            purth.setTh034(purthDto.getJysl());
            purth.setTh038(jhdDto.getCreator());
            purth.setTh042("********************");
            purth.setTh043("N");
            purth.setTh044("N");
            //TODO 这边取得不够完善
            purth.setTh045(DJ * purthDto.getJysl());
            BigDecimal MA064 = new BigDecimal(ma064);
            purth.setTh046(DJ * MA064.doubleValue());
            purth.setTh047(DJ * purthDto.getJysl());
            bbdkje += DJ * purthDto.getJysl();
            purth.setTh048(DJ * MA064.doubleValue());
            bbse += DJ * MA064.doubleValue();
            BigDecimal CD023 = (BigDecimal) list.get("CD023");
            purth.setTh049(CD023.doubleValue());
            jhbzsl += CD023.doubleValue();
            BigDecimal TAC03 = (BigDecimal) list.get("TAC03");
            purth.setTh050(TAC03.doubleValue());
            zysbzsl += TAC03.doubleValue();
            BigDecimal TA041 = (BigDecimal) list.get("TA041");
            purth.setTh051(TA041.doubleValue());
            purth.setTh052(0.00);
            purth.setTh054(0.000000);
            purth.setTh055(0.00);
            BigDecimal CD031 = (BigDecimal) list.get("CD031");
            purth.setTh058(CD031.doubleValue());
            BigDecimal CD032 = (BigDecimal) list.get("CD032");
            purth.setTh059(CD032.doubleValue());
            zjs += CD032.doubleValue();
            purth.setTh060(0.0000);
            BigDecimal TA025 = (BigDecimal) list.get("TA025");
            purth.setTh061(TA025.doubleValue());
            BigDecimal TA042 = (BigDecimal) list.get("TA042");
            purth.setTh062(TA042.doubleValue());
            String jjdw = purthMapper.getJJDW((String) list.get("CD004"));
            if (jjdw == null || jjdw.isEmpty()) {
                purth.setTh064((String) list.get("CD021"));
            } else {
                purth.setTh064(jjdw);
            }
            purth.setTh065((String) list.get("CD021"));
            BigDecimal TA007 = (BigDecimal) list.get("TA007");
            purth.setTh068(TA007.doubleValue());
            BigDecimal TA031 = (BigDecimal) list.get("TA031");
            purth.setTh069(TA031.doubleValue());
            purth.setTh070("N");
            BigDecimal TA028 = (BigDecimal) list.get("TA028");
            //TODO 折算率很怪
            purth.setTh071(1.0000);
            purth.setTh072("##########");
            purth.setTh077(0.000000);
            purth.setTh078(0.000000);
            purth.setTh079(0.000000);
            purth.setTh080("N");
            purth.setThc01(0.0);
            purth.setThc02("2");
            purth.setThc03((String) list.get("TA001"));
            purth.setThc04((String) list.get("TA002"));
            purth.setThc05((String) list.get("TA003"));
            purth.setThc06((String) list.get("TAC04"));
            purth.setThc07("0001");
            purths.add(purth);
//            这四位不能重复
            // 设置数据
            //todo  ------------------------------------------------------
            wmsInvml = wmsInvmlMapper.selectOne(new QueryWrapper<WmsInvml>()
                    .eq("ML001", purth.getTh004())
                    .eq("ML002", purth.getTh009())
                    .eq("ML003", purthDto.getKw())
                    .eq("ML004", purth.getTh010()));
            if (wmsInvml == null) {
                wmsInvml = new WmsInvml();
                wmsInvml.setMl001(purth.getTh004());//品号
                wmsInvml.setMl002(purth.getTh009());//仓库
                wmsInvml.setMl003(purthDto.getKw());//库位
                wmsInvml.setMl004(purth.getTh010());//批号
                wmsInvml.setMl005(purth.getTh015());//库存数量
                wmsInvml.setMl006(purth.getTh015());//库存包装数量
                wmsInvml.setMl009(purth.getTh014());//最近入库日
                wmsInvml.setMl010(purth.getTh014());
                wmsInvmlMapper.insert(wmsInvml);
            } else {
                Double t = wmsInvml.getMl005() + purth.getTh015();
                wmsInvml.setMl005(t);//把品号信息档里的库存量加上退料量
                wmsInvmlMapper.update(wmsInvml, new QueryWrapper<WmsInvml>()
                        .eq("ML001", wmsInvml.getMl001())
                        .eq("ML002", wmsInvml.getMl002())
                        .eq("ML003", wmsInvml.getMl003())
                        .eq("ML004", wmsInvml.getMl004()));
            }
            //todo

//                wmsInvml.setMl001(purth.getTh004());
//                wmsInvml.setMl002(purth.getTh009());
//                wmsInvml.setMl003(purthDto.getKw());
//                wmsInvml.setMl004(purth.getTh010());
//                wmsInvml.setMl005(purth.getTh015());
//                wmsInvml.setMl006(purth.getTh015());
//                wmsInvml.setMl008(purth.getTh014());
//                wmsInvml.setMl009(purth.getTh014());
//                wmsInvml.setMl010(purth.getTh014());
//                wmsInvmls.add(wmsInvml);
            wmsInvla.setLa001(purth.getTh004());
            wmsInvla.setLa004(purth.getTh014());
//            这四位不能重复
            wmsInvla.setLa005(1.0);
            wmsInvla.setLa006(jhdDto.getDb());
            wmsInvla.setLa007(purthDto.getDhjydh());
            wmsInvla.setLa008(purthDto.getXh());

            wmsInvla.setLa009(purthDto.getCw());
            wmsInvla.setLa010(purthDto.getBz());
            wmsInvla.setLa011(purth.getTh015());
            wmsInvla.setLa012(0.0);
            wmsInvla.setLa013(0.0);
            wmsInvla.setLa014("1");
            wmsInvla.setLa015("");
            wmsInvla.setLa016(purth.getTh010());
            wmsInvla.setLa017(0.0);
            wmsInvla.setLa018(0.0);
            wmsInvla.setLa019(0.0);
            wmsInvla.setLa020(0.0);
            wmsInvla.setLa021(0.0);
            wmsInvla.setLa022(purth.getTh004());
            wmsInvla.setLa023(purthDto.getKw());
            wmsInvla.setLa024("");
            wmsInvlas.add(wmsInvla);
            System.out.println(wmsInvlas);
        }
//        TODO 进货金额需要去采购单里面取
        purtg.setTg017(jhje);
        purtg.setTg018(kkje);
        purtg.setTg019(jhje * purma.getMA064().doubleValue());
        purtg.setTg020(0.00);
        purtg.setTg021(purma.getMA003());
        purtg.setTg022(purma.getMA005());
        purtg.setTg023("1");
        purtg.setTg023("N");
        purtg.setTg025(zjs);
        purtg.setTg026(zyssl);
        purtg.setTg028(jhje);
        purtg.setTg030(purma.getMA064().doubleValue());
        purtg.setTg031(bbdkje);
        purtg.setTg032(bbse);
        purtg.setTg033(purma.getMA055());
        purtg.setTg038(0.000000);
        purtg.setTg039(0.000000);
        purtg.setTg040(zysbzsl);
        purtg.setTg041(0.000000);
        purtg.setTg042("N");
        purtg.setTg045(0.0);
        purtg.setTg046(0.0);
        purtg.setTg050("N");
        purtg.setTg053(jhsl);
        purtg.setTg054(jhbzsl);
        purtg.setTg055(0.000000);
        purtg.setTg058("0");
        purtg.setTg059("********************");

        Boolean bool = purtgMapper.insertPurtg(purtg);
        if (!bool) {
            return Result.fail().message("插入进货单单头失败");
        }
        for (Purth purth1 : purths) {
            bool = purthMapper.insertPurth(purth1);
        }
        if (!bool) {
            return Result.fail().message("插入进货单单身失败");
        }
        String nowTime = TimeUtils.getNowTime();
        // 判断审核源是否打开
        ShenHe shenHe = new ShenHe();
        //shenHe.setCom(moctc.getCompany());
        shenHe.setCom("ZJQH");
        shenHe.setProgram("PURI09");//进货单审核
        shenHe.setDb(purtg.getTg001());
        shenHe.setDh(purtg.getTg002());
        shenHe.setRq(nowTime.substring(0, 8));
        shenHe.setType("DO");
        shenHe.setUser("");//自动审核的审核人要设置成登录者的员工编号

        //String url = "http://" + RunHttp.getIp() + ":9000/api/yifei/audit";
        String url = "http://" + "192.168.0.141" + ":9000/api/yifei/audit";
        String jsonString = JSON.toJSONString(shenHe);

        String ans = null;
        try {
            System.out.println("-------这里是请求的json值" + jsonString);
            ans = HttpClientUtil.postRequest(url, jsonString);
        } catch (IOException e) {
            return Result.fail().message("自动审核发生异常，已经被捕获！");
        }
        HttpResult httpResult;
        if (ans == null) {
            return Result.fail().message("失败：出现异常请查看审批后台是否开启！");
        } else {
            ans = ans.replace("\\r", "");
            httpResult = JSON.parseObject(ans, HttpResult.class);
            System.out.println("这里是响应结果的json数据: " + httpResult);
        }
        if (httpResult.getStatus().equals("失败")) {
            return Result.fail().message("审核失败！\\n" + "原因：" + httpResult.getReason() + "\\n 详情：" + httpResult.getDetail());
        }

        //        int i1 = 0;
//        for (WmsInvml wmsInvml1 : wmsInvmls) {
//            // 先拿这个品号（ml001）去判断，没有就设置数据插入
//            WmsInvml existingWmsInvml = wmsInvmlMapper.selectById(wmsInvml1.getMl001());
//            if (existingWmsInvml == null) {
//                wmsInvmlMapper.insert(wmsInvml1);
//            }
//        }

//        if (i1 == 0){
//            return "插入WmsInvml失败";
//        }
        int i2 = 0;
        for (WmsInvla wmsInvla1 : wmsInvlas) {
            i2 += wmsInvlaMapper.insert(wmsInvla1);
        }
        if (i2 == 0) {
            return Result.fail().message("插入WmsInvla失败");
        }
        String docNo = "";
        docNo = purtg.getTg001() + '-' + purtg.getTg002();
        return Result.ok().message(docNo);
    }

    @Override
    public PageInfo<NeedArrivalInsVo> getNeedArrivalIns(NeedArrivalInsDto needArrivalInsDto) {
        PageHelper.startPage(needArrivalInsDto.getPage(), needArrivalInsDto.getSize());
//        System.out.println("异常测试点1");
//        String starttime;
//        String endtime;
//        if (needArrivalInsDto.getTime()!=null && ! needArrivalInsDto.getTime().isEmpty()){
//            String[] dateArray = needArrivalInsDto.getTime().split("-");
//            starttime = dateArray[0];
//            endtime = dateArray[1];
//        }else {
//            starttime=null;
//            endtime=null;
//        }
//        needArrivalInsDto.setStartTime(starttime);
//        needArrivalInsDto.setEndTime(endtime);
//        System.out.println("startTime: " + needArrivalInsDto.getStartTime());
//        System.out.println("endTime: " + needArrivalInsDto.getEndTime());
        if (com.mgkj.common.utils.StringUtils.isNotEmpty(needArrivalInsDto.getSupplierNo()))
            needArrivalInsDto.setSupplierNo(needArrivalInsDto.getSupplierNo().trim());
        List<NeedArrivalInsVo> needArrivalIns = enterStorageMapper.getNeedArrivalIns(needArrivalInsDto);
        PageInfo<NeedArrivalInsVo> pageInfo = new PageInfo<>(needArrivalIns);
        return pageInfo;
    }

    @Override
    public Map<String, String> arrivalInvoiceBatch(List<InspectDto> inspectDtos) {
        Map<String, String> map1 = new HashMap<>();
        for (InspectDto inspectDto : inspectDtos) {
            Qmsta qmsta = new Qmsta();
            String company = commonMapper.getCompany();
            qmsta.setCOMPANY(company);
            qmsta.setCREATOR(inspectDto.getCreator());
            String usrGroup = commonMapper.getUsrGroup(inspectDto.getCreator());
            qmsta.setUSR_GROUP(usrGroup);
            // 获取当前时间
            LocalDateTime currentTime = LocalDateTime.now();

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

            // 格式化时间
            String formattedTime = currentTime.format(formatter);
            String yyyyMMdd = currentTime.format(formatter1);
            String create_date = currentTime.format(formatter2);
            qmsta.setCREATE_DATE(create_date);
            BigDecimal flag = new BigDecimal("0");
            qmsta.setFLAG(flag);
            qmsta.setTa001(inspectDto.getDhdb());
            qmsta.setTa002(inspectDto.getDhdh());
            qmsta.setTa003(inspectDto.getXh());
            qmsta.setTa004(yyyyMMdd);
            Map<String, Object> map = enterStorageMapper.getNeedInspectByDH(inspectDto.getDhdb(), inspectDto.getDhdh(), inspectDto.getXh());
            map = map == null ? new HashMap<>() : map;
            qmsta.setTa005(map.get("CC003") == null ? "" : map.get("CC003").toString());
            qmsta.setTa006(inspectDto.getCreator());
            qmsta.setTa007(inspectDto.getBreakNumber());//破坏数
            qmsta.setTa008(inspectDto.getReturnNumber());//验退数
            qmsta.setTa009(0.00);//扣款金额
            //TODO TA011 TA012有待商榷
            qmsta.setTa011("2");//判定(2:允收/3:拒收/4:特采/5.进行复检)
            qmsta.setTa012("2");//0.免检、1.减量、2.正常、3.加严、4.全检
            qmsta.setTa013(0.0);//打印次数
            qmsta.setTa014("Y");
            qmsta.setTa015(inspectDto.getRemark());
            qmsta.setTa019(yyyyMMdd);
            qmsta.setTa020(inspectDto.getCreator());
            qmsta.setTa021("N");
            qmsta.setTa022(0.000000);//总抽样数量
            qmsta.setTa023(0.000000);// 不良数量合计
            qmsta.setTa024(0.0);//传送次数
            qmsta.setTa025(inspectDto.getScrapNumber());//报废数量
            qmsta.setTa026("0001");//次数
            qmsta.setTa027("到货验收单PURCAI02");
            //TODO 折算率都是0没有获取
            qmsta.setTa028(0.0000);
            qmsta.setTa029(yyyyMMdd);
            qmsta.setTa031(inspectDto.getBreakPackageNumber());
            qmsta.setTa032(0.000000);
            qmsta.setTa033(0.000000);
            qmsta.setTa034("N");
            qmsta.setTa035((String) map.get("CD007"));
            qmsta.setTa041(inspectDto.getReturnPackageNumber());
            qmsta.setTa042(inspectDto.getScrapPackageNumber());
            qmsta.setTa043(0.000000);
            qmsta.setTa044(0.000000);
            qmsta.setTa045(0.000000);
            qmsta.setTac01(inspectDto.getAccNumber());
            qmsta.setTac02(0.000000);
            qmsta.setTac03(inspectDto.getAccPackageNumber());
            Integer jypc = enterStorageMapper.getJYPC(inspectDto.getDhdb(), inspectDto.getDhdh(), inspectDto.getXh());
            if (jypc == null) {
                qmsta.setTac04("0001");
            } else {
                qmsta.setTac04(String.format("%04d", jypc));
            }
            BigDecimal zero = new BigDecimal("0.000000");
            qmsta.setUDF51(zero);
            qmsta.setUDF52(zero);
            qmsta.setUDF53(zero);
            qmsta.setUDF54(zero);
            qmsta.setUDF55(zero);
            qmsta.setUDF56(zero);
            qmsta.setUDF57(zero);
            qmsta.setUDF58(zero);
            qmsta.setUDF59(zero);
            qmsta.setUDF60(zero);
            qmsta.setUDF61(zero);
            qmsta.setUDF62(zero);
            Boolean bool = enterStorageMapper.insertQMSTA(qmsta);
            if (!bool) {
                map1.put(inspectDto.getDhdb() + inspectDto.getDhdh() + inspectDto.getXh(), "检验单生成失败");
            }
            bool = enterStorageMapper.updatePurcd(inspectDto.getAccNumber(), inspectDto.getAccPackageNumber(),
                    inspectDto.getBreakNumber(), inspectDto.getReturnNumber(),
                    inspectDto.getScrapNumber(), inspectDto.getScrapPackageNumber(),
                    inspectDto.getReturnPackageNumber(), inspectDto.getBreakPackageNumber(),
                    inspectDto.getDhdb(), inspectDto.getDhdh(), inspectDto.getXh());
            if (!bool) {
                map1.put(inspectDto.getDhdb() + inspectDto.getDhdh() + inspectDto.getXh(), "到货单更新失败");
                enterStorageMapper.deleteQMSTA(qmsta);
            }
            map1.put(inspectDto.getDhdb() + inspectDto.getDhdh() + inspectDto.getXh(), "到货单检验完成，总到货量：" + map.get("CD008") + "此次检验：" + inspectDto.getAccNumber());
        }
        return map1;
    }

    @Override
    public Result insertjhdBatch(InitJhdDto jhdDto) throws UnknownHostException {
        //1、进行插入前删除等处理
        DynamicDataSourceContextHolder.push(jhdDto.getCompany());
        boolean flag = false;
        String dh = "";
        String creator =jhdDto.getInitPurthDtoList().get(0).getCreator();
        if(com.mgkj.common.utils.StringUtils.isEmpty(creator)) {
            return Result.fail().message("抓不到登录者，请重新登录。");
        }
        String usrGroup = commonMapper.getUsrGroup(creator);
        Dscmb dscmb = dscmbMapper.selectOne(new QueryWrapper<Dscmb>().eq("MB003", jhdDto.getCompany()));
        String company = dscmb.getMB001().trim();
        Purtg purtg = new Purtg();
        Integer count = purtgMapper.selectCount(new QueryWrapper<Purtg>()
                .eq("TG002", jhdDto.getTG002())
                .eq("TG001", jhdDto.getTG001())
                .eq("TG013", "Y"));
        if (count >= 1) {
            return Result.fail().message("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据");
        }
        //查询数据库中是否存在未审核的相同单据号的进货单
        Integer count1 = purtgMapper.selectCount(new QueryWrapper<Purtg>()
                .eq("TG002", jhdDto.getTG002())
                .eq("TG001", jhdDto.getTG001())
                .eq("TG013", "N"));
        if (count1 >= 1) {
            dh = jhdDto.getTG002();
            purtgMapper.delete(new QueryWrapper<Purtg>()
                    .eq("TG001", jhdDto.getTG001())
                    .eq("TG002", jhdDto.getTG002()));
            purthMapper.delete(new QueryWrapper<Purth>()
                    .eq("TH001", jhdDto.getTG001())
                    .eq("TH002", jhdDto.getTG002()));
        } else {
            Integer count2 = purtgMapper.selectCount(new QueryWrapper<Purtg>()
                    .eq("UDF12", jhdDto.getTG002()));
            if (count2 >= 1) {
                return Result.fail().message("此单号已存在!");
            } else {
                flag = true;
                dh = commonService.getIdByType(jhdDto.getTG001(), "PURTG");
                purtg.setUdf12(jhdDto.getTG002());
            }
        }
        //2、定义多个 Double 类型的变量，用于存储
        //进货金额、开票金额、总金额、总验收数量、本币到款金额、本币税额、总验收标准数量、进货数量和进货标准数量
        Double jhje = 0.0;
        Double kkje = 0.0;
        Double zjs = 0.0;
        Double zyssl = 0.0;
        Double bbdkje = 0.0;
        Double bbse = 0.0;
        Double zysbzsl = 0.0;
        Double jhsl = 0.0;
        Double jhbzsl = 0.0;

        purtg.setTg001(jhdDto.getTG001());


//        String idByType = commonService.getIdByType(jhdDto.getTG001(), "PURTG");
//        String dh = idByType;

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter create_date = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

        // 格式化时间
        String formattedTime = currentTime.format(formatter);
        String yyyyMMdd = currentTime.format(formatter1);

        //3、初始化 Map 对象，用于存储采购订单单身相关信息，
        Map<String, Object> list = new HashMap<>();
        purtg.setTg002(dh);

        purtg.setCompany(company);
//        purtg.setCreator(creator);
        //查询ADMMF-用户信息，MF004组编号
//        purtg.setUsrGroup(usrGroup);
        purtg.setCreateDate(currentTime.format(create_date));
        purtg.setFlag("2");
        purtg.setTg003(jhdDto.getTG003());
        //工厂只有一个，先写死了
        purtg.setTg004(jhdDto.getTG004());
        purtg.setTg005(jhdDto.getTG005());

        //4、根据供应商代码查询 PURMA -供应商基本信息档
        LambdaQueryWrapper<PURMA> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PURMA::getMA001, jhdDto.getTG005());
        PURMA purma = purmaMapper.selectOne(wrapper);
        if (purma == null) return Result.fail().message("供应商不存在!");
        //设置币种Tg007
        purtg.setTg007(purma.getMA021());
        Double hl = 0.0;
        if (purma.getMA021().trim().equals("RMB")) {
            purtg.setTg008(1.0000000);
        } else {
            hl = enterStorageMapper.selectHL(purma.getMA021());
            purtg.setTg008(hl);
        }
        //发票种类
        //税种
        purtg.setTg009(purma.getMA030());
        purtg.setTg010(purma.getMA044());
//        打印次数
//        审核码
        purtg.setTg012(0.0);
        purtg.setTg013("N");

        purtg.setTg014(yyyyMMdd);
        purtg.setTg015("N");
        List<Purth> purths = new ArrayList<>();
        List<InitPURTHDto> purchaseDtos = jhdDto.getInitPurthDtoList();
        for (InitPURTHDto purchaseDto : purchaseDtos) {
//            purchaseDto.setCreator(creator);
//            purchaseDto.setUsrGroup(usrGroup);
            purchaseDto.setCompany(company);
            Purth purth = new Purth();
            Integer pd = enterStorageMapper.isPurchaseOrder(purchaseDto.getTH011(), purchaseDto.getTH012(), purchaseDto.getTH013(), purtg.getTg005());
            if (pd <= 0) {
                return Result.fail(purchaseDto.getTH011() + '_' + purchaseDto.getTH012() + '_' + purchaseDto.getTH013() + "采购单已完结或不存在").message(purchaseDto.getTH011() + '_' + purchaseDto.getTH012() + '_' + purchaseDto.getTH013() + "采购单已完结或不存在");
            } else {
                list = enterStorageMapper.SelectByPur3(purma.getMA044(), purchaseDto.getTH011(), purchaseDto.getTH012(), purchaseDto.getTH013(), purtg.getTg005());
            }
            if (list != null) {
                list = enterStorageMapper.SelectByPur2(purma.getMA044(), purchaseDto.getTH011(), purchaseDto.getTH012(), purchaseDto.getTH013(), purtg.getTg005());
                if (list == null) {
                    return Result.fail("采购单已交数量>采购数量,采购单已结束").message("采购单已交数量>采购数量,采购单已结束");
                }
            } else {
                return Result.fail(purchaseDto.getTH011() + '_' + purchaseDto.getTH012() + '_' + purchaseDto.getTH013() + "采购单不存在").message(purchaseDto.getTH011() + '_' + purchaseDto.getTH012() + '_' + purchaseDto.getTH013() + "采购单不存在");
            }
            purth.setCompany(company);
//            purth.setCreator(creator);
//            purth.setUsrGroup(usrGroup);
            purth.setCreateDate(currentTime.format(create_date));
            purth.setFlag("2");
            purth.setTh001(purchaseDto.getTH001());
            purth.setTh002(dh);
            purth.setTh003(purchaseDto.getTH003());
            purth.setTh004(purchaseDto.getTH004());
            Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().eq("MB001", purchaseDto.getTH004()));
            purth.setTh005(invmb.getMb002());
            purth.setTh006(invmb.getMb003());
            //
            BigDecimal bigDecimal1 = (BigDecimal) list.get("TD008");
            BigDecimal bigDecimal2 = (BigDecimal) list.get("TD015");
            Double sum = bigDecimal1.doubleValue() - bigDecimal2.doubleValue();
            if (purchaseDto.getTH007() == null) {
                //进货数量
                purth.setTh007(sum);
                jhsl += sum;
            } else {
                purth.setTh007(purchaseDto.getTH007());
                jhsl += purchaseDto.getTH007();
            }
            purth.setTh008(purchaseDto.getTH008());
            purth.setTh009(purchaseDto.getTH009());
            purth.setTh010(purchaseDto.getTH010());
            purth.setTh011(purchaseDto.getTH011());
            purth.setTh012(purchaseDto.getTH012());
            purth.setTh013(purchaseDto.getTH013());

            //进货数量回写对应采购单身的已交数量
//            int c = purtcdMapper.updateTD015(purth);
//            if (c<=0){
//                return Result.fail(purchaseDto.getTH011() + '_' + purchaseDto.getTH012() + '_' + purchaseDto.getTH013() + "采购单身交货数会写失败!").message(purchaseDto.getTH011() + '_' + purchaseDto.getTH012() + '_' + purchaseDto.getTH013() + "采购单身交货数会写失败!");
//            }

            purth.setTh014(purchaseDto.getTH014());
            purth.setTh015(purchaseDto.getTH015());
            zyssl += purchaseDto.getTH015();
            Double jjsl = purchaseDto.getTH016();
            purth.setTh016(jjsl);
            purth.setTh017(0.000000);
            Double DJ = 0.0;
            DJ = enterStorageMapper.selectOne(purchaseDto.getTH011(), purchaseDto.getTH012(), purchaseDto.getTH013());
            purth.setTh018(DJ);
            InitRaxDto raxDto = new InitRaxDto(purma.getMA044(),
                    BigDecimal.valueOf(purchaseDto.getTH016()),
                    purma.getMA064(),
                    BigDecimal.valueOf(DJ),
                    BigDecimal.valueOf(hl));
            InitRaxVo rax = InitMoneyUtils.getRax(raxDto);
            purth.setTh019(rax.getPrice().doubleValue());
            jhje += purth.getTh019();
            purth.setTh020(0.000000);
            kkje = 0.000000;
            purth.setTh024(0.00);
            purth.setTh026("N");
            Boolean CQ = enterStorageMapper.selectCQ((String) list.get("TD001"), (String) list.get("TD002"), (String) list.get("TD003"));
            if (CQ) {
                purth.setTh027("Y");
            } else {
                purth.setTh027("N");
            }
            purth.setTh028(purchaseDto.getTH028());
            purth.setTh029("N");
            purth.setTh030(purchaseDto.getTH030());
            purth.setTh031("N");
            purth.setTh032("N");
            purth.setTh034(purchaseDto.getTH015());
            purth.setTh038("MES");
            purth.setTh043("N");
            purth.setTh044("N");
            //TODO 这边取得不够完善
            purth.setTh045(rax.getPriceBeforeTax().doubleValue());
            purth.setTh046(rax.getTaxPrice().doubleValue());
            purth.setTh047(rax.getPriceBeforeTaxLocal().doubleValue());
            bbdkje += rax.getPriceBeforeTax().doubleValue();
            purth.setTh048(rax.getTaxPriceLocal().doubleValue());
            bbse += rax.getTaxPriceLocal().doubleValue();
            BigDecimal td030 = (BigDecimal) list.get("TD030");
            BigDecimal td031 = (BigDecimal) list.get("TD031");
            purth.setTh049(td030.doubleValue() - td031.doubleValue());
            jhbzsl += td030.doubleValue() - td031.doubleValue();
            purth.setTh050(td030.doubleValue() - td031.doubleValue());
            zysbzsl += td030.doubleValue() - td031.doubleValue();
            purth.setTh051(0.00);
            purth.setTh052(0.00);
            purth.setTh053((String) list.get("TD032"));
            purth.setTh054(0.000000);
            purth.setTh055(0.00);
            BigDecimal CD031 = (BigDecimal) list.get("TD036");
            purth.setTh058(CD031.doubleValue());
            BigDecimal CD032 = (BigDecimal) list.get("TD037");
            purth.setTh059(CD032.doubleValue());
            zjs += CD032.doubleValue();
            purth.setTh060(0.0000);
            purth.setTh061(0.00);
            purth.setTh062(0.00);
            purth.setTh064((String) list.get("TD038"));
            purth.setTh065((String) list.get("TD009"));
            purth.setTh068(0.000000);
            purth.setTh069(0.000000);
            purth.setTh070("N");
            purth.setTh071(1.0000);
            purth.setTh072("##########");
            purth.setTh077(0.000000);
            purth.setTh078(0.000000);
            BigDecimal TD045 = (BigDecimal) list.get("TD045");
            BigDecimal TD046 = (BigDecimal) list.get("TD046");
            purth.setTh079(TD045.doubleValue() - TD046.doubleValue());
            purth.setTh080("N");
            BigDecimal TDC01 = (BigDecimal) list.get("TDC01");
            BigDecimal TDC02 = (BigDecimal) list.get("TDC02");
            purth.setThc01(TDC01.doubleValue() - TDC02.doubleValue());
            purth.setThc02("2");
            String td021 = enterStorageMapper.selectvv((String) list.get("CD010"), (String) list.get("CD011"), (String) list.get("CD012"));
            purth.setUdf01(td021); //订单号
            purth.setThc03(purchaseDto.getTHC03());
            purth.setThc04(purchaseDto.getTHC04());
            purth.setThc05(purchaseDto.getTHC05());
            purth.setThc06(purchaseDto.getTHC06());
            System.out.println("到货单别单号序号检验批次："+ (String) list.get("TA001") + " " + (String) list.get("TA002") + " " + (String) list.get("TA003") + " " + (String) list.get("TAC04"));
            System.out.println("到货单别单号序号检验批次："+ purchaseDto.getTHC03() + " " + purchaseDto.getTHC04() + " " + purchaseDto.getTHC05() + " " + purchaseDto.getTHC06());


            purths.add(purth);
        }
        //TODO 进货金额需要去采购单里面取
        purtg.setTg017(jhje);
        purtg.setTg018(kkje);
        purtg.setTg019(jhje * purma.getMA064().doubleValue());
        purtg.setTg020(0.00);
        purtg.setTg021(purma.getMA003());
        purtg.setTg022(purma.getMA005());
        purtg.setTg023("1");
        purtg.setTg023("N");
        purtg.setTg025(zjs);
        purtg.setTg026(zyssl);
        purtg.setTg028(jhje);
        purtg.setTg030(purma.getMA064().doubleValue());
        purtg.setTg031(bbdkje);
        purtg.setTg032(bbse);
        purtg.setTg033(purma.getMA055());
        purtg.setTg038(0.000000);
        purtg.setTg039(0.000000);
        purtg.setTg040(zysbzsl);
        purtg.setTg041(0.000000);
        purtg.setTg042("N");
        purtg.setTg045(0.0);
        purtg.setTg046(0.0);
        purtg.setTg050("N");
        purtg.setTg053(jhsl);
        purtg.setTg054(jhbzsl);
        purtg.setTg055(0.000000);
        purtg.setTg058("0");

        purtgMapper.insert(purtg);
        for (Purth purth : purths) {
            purthMapper.insert(purth);
        }

        Integer i = purthMapper.selectCount(new QueryWrapper<Purth>().eq("TH001", jhdDto.getTG001())
                .eq("TH002", dh));
        if (i == null || i <= 0) {
            purtgMapper.delete(new QueryWrapper<Purtg>().eq("TG001", jhdDto.getTG001())
                    .eq("TH002", dh));
            return Result.fail().message("单身生成失败");
        }

        ShenHe shenHe = new ShenHe();
        shenHe.setCom(company);
        shenHe.setProgram("PURI09");
        shenHe.setUser(creator);
        shenHe.setDb(jhdDto.getTG001());
        shenHe.setDh(dh);
        shenHe.setType("DO");
        shenHe.setRq(yyyyMMdd);

        InetAddress localhost = InetAddress.getLocalHost();
//        String ipAddress = localhost.getHostAddress();
//        String url = "http://" + ipAddress + ":9000/api/yifei/audit";
        String url = "http://" + "192.168.0.141" + ":9000/api/yifei/audit";


        String jsonString = JSON.toJSONString(shenHe);
        String ans = null;
        try {
//            ShenHe anss=restTemplate.postForObject(url,shenHe,ShenHe.class);
            ans = HttpClientUtil.postRequest(url, jsonString);
        } catch (Exception e) {
            if (flag) {
//                enterStorageMapper.deletePurtg(purtg);
//                for (Purth purth1 : purths) {
//                    enterStorageMapper.deletePurth(purth1);
//                }
            }
            log.info("出现异常请查看审批后台是否开启");
            return Result.fail("出现异常请查看审批后台是否开启").message("出现异常请查看审批后台是否开启");
        }
        HttpResult httpResult = new HttpResult();

        if (ans == null) {
            return Result.fail("出现异常请查看审批后台是否开启").message("出现异常请查看审批后台是否开启");
        } else {
            httpResult = JSON.parseObject(ans, HttpResult.class);
//            System.out.println("httpResult: " + httpResult);
        }
        if (httpResult.getStatus().equals("失败")) {
            if (flag) {
//                enterStorageMapper.deletePurtg(purtg);
//                for (Purth purth1 : purths) {
//                    enterStorageMapper.deletePurth(purth1);
//                }
            }
            return Result.fail(httpResult.getReason() + httpResult.getDetail()).message(httpResult.getReason() + httpResult.getDetail());
        }

        //插入wmsl两表
        Boolean b = this.wmsinsertpurth(purchaseDtos);
        if (!b) {
            enterStorageMapper.deletePurtg(purtg);
            for (Purth purth1 : purths) {
                enterStorageMapper.deletePurth(purth1);
            }
            return Result.fail("wms_invla和wms_invml插入失败！").message("wms_invla和wms_invml插入失败！");
        }


        return Result.ok("单据生成成功:" + jhdDto.getTG001() + '_' + dh);
    }

    @Transactional
    public Boolean wmsinsertpurth(List<InitPURTHDto> purths) {
        List<WmsInvml> invmlList = new ArrayList<>();
        List<WmsInvla> wmsInvlas = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        // 将 LocalDateTime 对象格式化为字符串
        String formattedDateTime = now.format(formatter2);
        boolean result = true;
        for (InitPURTHDto purth : purths) {
            //库位可以不存在
            if (purth.getKwInfo() == null || purth.getKwInfo().isEmpty()) {
                result = insertByTh072(now, formattedDateTime, purth, invmlList, wmsInvlas);
            } else {
                for (KWAndNum kwAndNum : purth.getKwInfo()) {
                    purth.setTH015(kwAndNum.getNum());
                    purth.setTH072(kwAndNum.getKw());
                    result = insertByTh072(now, formattedDateTime, purth, invmlList, wmsInvlas);
                    if (!result) return result;
                }
            }
            if (!result) return result;
        }
        return result;
    }

    @Override
    public Result insertBackByArrBatch(InitThdDto initThdDto) throws UnknownHostException {
        DynamicDataSourceContextHolder.push(initThdDto.getCompany());
        boolean flag = false;
        String dh = "";
        InitPurti purti = new InitPurti();
        Integer count = initPurtiMapper.selectCount(new QueryWrapper<InitPurti>()
                .eq("TI001", initThdDto.getTI001())
                .eq("TI002", initThdDto.getTI002())
                .eq("TI013", "Y"));
        if (count >= 1) {
            return Result.fail("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据");
        }
        Dscmb dscmb = dscmbMapper.selectOne(new QueryWrapper<Dscmb>().eq("MB003", initThdDto.getCompany()));
        String company = dscmb.getMB001().trim();
        Integer count1 = initPurtiMapper.selectCount(new QueryWrapper<InitPurti>()
                .eq("TI001", initThdDto.getTI001())
                .eq("TI002", initThdDto.getTI002())
                .eq("TI013", "N"));
        if (count1 >= 1) {
            dh = initThdDto.getTI002();
            initPurtiMapper.delete(new QueryWrapper<InitPurti>()
                    .eq("TI001", initThdDto.getTI001())
                    .eq("TI002", initThdDto.getTI002()));
            initPurtjMapper.delete(new QueryWrapper<InitPurtj>()
                    .eq("TJ001", initThdDto.getTI001())
                    .eq("TJ002", initThdDto.getTI002()));
        } else {
            Integer count2 = initPurtiMapper.selectCount(new QueryWrapper<InitPurti>()
                    .eq("UDF12", initThdDto.getTI002()));
            if (count2 >= 1) {
                return Result.fail("此单号已存在");
            } else {
                flag = true;
                dh = commonService.getIdByType(initThdDto.getTI001(), "PURTI");
                purti.setUdf12(initThdDto.getTI002());
            }
        }
        Map<String, String> map = new HashMap<>();
        double sumPriceY = 0.0;
        double ratePriceY = 0.0;
        double sumPrice = 0.0;
        double ratePrice = 0.0;
        double sumNum = 0.0;

        purti.setCompany(company);
        purti.setCreator("MES");
        purti.setUsrGroup(commonMapper.getUsrGroup("MES"));
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        DateTimeFormatter formatter = ofPattern("yyyyMM");
        DateTimeFormatter formatter1 = ofPattern("yyyyMMdd");
        DateTimeFormatter create_date = ofPattern("yyyyMMddHHmmssSSS");

        // 格式化时间
        String yyyyMMdd = currentTime.format(formatter1);
        purti.setCreateDate(currentTime.format(create_date));
        purti.setFlag(1.0);
        purti.setTi001(initThdDto.getTI001());
        purti.setTi002(dh);
        purti.setTi003(yyyyMMdd);
        purti.setTi004(initThdDto.getTI004());
        purti.setTi005(initThdDto.getTI005());
        PURMA purma = enterStorageMapper.selectPURMA(initThdDto.getTI004());
        if (purma == null) return Result.fail("供应商不存在");
        purti.setTi006(purma.getMA021());
        Double hl = 0.0;
        if (purma.getMA021().trim().equals("RMB")) {
            purti.setTi007(1.0000000);
        } else {
            hl = enterStorageMapper.selectHL(purma.getMA021());
            purti.setTi007(hl);
        }
        purti.setTi008(purma.getMA030());
        purti.setTi009(purma.getMA044());
        purti.setTi010(0.0);
        List<InitThdBodyDto> thdBodyDto = initThdDto.getThdBodyDto();
        List<InitPurtj> list = new ArrayList<>();
        for (InitThdBodyDto bodyDto : thdBodyDto) {
            InitPurtj purtj = new InitPurtj();
            purtj.setCompany(company);
            purtj.setCreator(purti.getCreator());
            purtj.setUsrGroup(purti.getUsrGroup());
            purtj.setCreateDate(purti.getCreateDate());
            purtj.setFlag(purti.getFlag());
            purtj.setTj001(bodyDto.getTJ001());
            purtj.setTj002(dh);
            purtj.setTj003(bodyDto.getTJ003());
            purtj.setTj004(bodyDto.getTJ004());
            Map<String, Object> map1 = enterStorageMapper.getOrderInfo(bodyDto.getTJ004());
            purtj.setTj005((String) map1.get("MB002"));
            purtj.setTj006((String) map1.get("MB003"));
            purtj.setTj007(bodyDto.getTJ007());
            purtj.setTj016(bodyDto.getTJ016());
            purtj.setTj017(bodyDto.getTJ017());
            purtj.setTj018(bodyDto.getTJ018());
            if (StringUtils.isNotBlank(bodyDto.getTJ016()) && StringUtils.isNotBlank(bodyDto.getTJ017()) && StringUtils.isNotBlank(bodyDto.getTJ018())) {
                InitPurtd purtd = initPurtdMapper.selectOne(new QueryWrapper<InitPurtd>()
                        .eq("TD001", bodyDto.getTJ016())
                        .eq("TD002", bodyDto.getTJ017())
                        .eq("TD003", bodyDto.getTJ018()));
                purtj.setTj008(purtd.getTd010());
            } else {
                purtj.setTj008(0.0);
            }
            purtj.setTj009(bodyDto.getTJ009());
            sumNum += bodyDto.getTJ009();
            InitRaxDto initRaxDto = new InitRaxDto(purma.getMA044(),
                    BigDecimal.valueOf(bodyDto.getTJ048()),
                    purma.getMA064(),
                    BigDecimal.valueOf(purtj.getTj008()),
                    BigDecimal.valueOf(hl));
            InitRaxVo rax = InitMoneyUtils.getRax(initRaxDto);
            purtj.setTj010(rax.getPrice().doubleValue());
            purtj.setTj011(bodyDto.getTJ011());
            purtj.setTj012("********************");
            purtj.setTj020(bodyDto.getTJ020());
            purtj.setTj021("N");
            purtj.setTj022(bodyDto.getTJ009());
            purtj.setTj024(0.000000);
            purtj.setTj028("N");
            purtj.setTj030(rax.getPriceBeforeTax().doubleValue());
            sumPriceY += rax.getPriceBeforeTax().doubleValue();
            purtj.setTj031(rax.getTaxPrice().doubleValue());
            ratePriceY += rax.getTaxPrice().doubleValue();
            purtj.setTj032(rax.getPriceBeforeTaxLocal().doubleValue());
            sumPrice += rax.getPriceBeforeTaxLocal().doubleValue();
            purtj.setTj033(rax.getTaxPriceLocal().doubleValue());
            ratePrice += rax.getTaxPriceLocal().doubleValue();
            purtj.setTj035("1");
            purtj.setTj036(0.0);
            purtj.setTj039(0.000000);
            purtj.setTj040(0.000000);
            purtj.setTj041(purma.getMA064().doubleValue());
            purtj.setTj046("##########");
            purtj.setTj047(bodyDto.getTJ047());
            purtj.setTj048(bodyDto.getTJ048());
            purtj.setTj049((String) map1.get("MB004"));
            purtj.setTj053(0.000000);
            purtj.setTj054(0.000000);
            purtj.setTj055(0.000000);
            purtj.setTj056("N");
            purtj.setTjc01("2");
            purtj.setTjc02(0.000000);
            list.add(purtj);
        }
        purti.setTi011(sumPriceY);
        purti.setTi013(initThdDto.getTI013());
        purti.setTi014(yyyyMMdd);
        purti.setTi015(ratePriceY);
        purti.setTi016(purma.getMA003());
        purti.setTi017(purma.getMA005());
        purti.setTi019("1");
        purti.setTi020("N");
        purti.setTi021(0.0);
        purti.setTi022(sumNum);
        purti.setTi024("N");
        purti.setTi026("MES");
        purti.setTi027(purma.getMA064().doubleValue());
        purti.setTi028(sumPrice);
        purti.setTi029(ratePrice);
        purti.setTi031(0.000000);
        purti.setTi032("N");
        purti.setTi034(0.0);
        purti.setTi036("N");
        purti.setTi040("N");
        initPurtiMapper.insert(purti);
        for (InitPurtj purtj : list) {
            initPurtjMapper.insert(purtj);
        }

        Integer i = initPurtjMapper.selectCount(new QueryWrapper<InitPurtj>()
                .eq("TJ001", initThdDto.getTI001())
                .eq("TJ002", dh));
        if (i == null || i <= 0) {
            initPurtiMapper.delete(new QueryWrapper<InitPurti>()
                    .eq("TI001", initThdDto.getTI001())
                    .eq("TI002", dh));
            return Result.fail("单身生成失败");
        }

        ShenHe shenHe = new ShenHe();
        shenHe.setCom(company);
        shenHe.setProgram("PURI11");
        shenHe.setUser("MES");
        shenHe.setDb(initThdDto.getTI001());
        shenHe.setDh(dh);
        shenHe.setType("DO");
        shenHe.setRq(yyyyMMdd);

        InetAddress localhost = InetAddress.getLocalHost();
        String ipAddress = localhost.getHostAddress();
        String url = "http://" + ipAddress + ":9000/api/yifei/audit";


        String jsonString = JSON.toJSONString(shenHe);
        String ans = null;
        HttpResult httpResult = new HttpResult();
        try {
//            ShenHe anss=restTemplate.postForObject(url,shenHe,ShenHe.class);
            ans = HttpClientUtil.postRequest(url, jsonString);
            httpResult = JSON.parseObject(ans, HttpResult.class);
            if (httpResult.getStatus().equals("失败")) {
                if (flag) {
                    initPurtiMapper.delete(new QueryWrapper<InitPurti>()
                            .eq("TI001", initThdDto.getTI001())
                            .eq("TI002", dh));
                    for (InitPurtj purtj : list) {
                        initPurtjMapper.delete(new QueryWrapper<InitPurtj>()
                                .eq("TJ001", purtj.getTj001())
                                .eq("TJ002", dh)
                                .eq("TJ003", purtj.getTj003()));
                    }
                }
                return Result.fail(httpResult.getReason() + httpResult.getDetail());
            }
        } catch (Exception e) {
            //System.out.println("出现异常请查看审批后台是否开启");
            log.info("出现异常请查看审批后台是否开启");
            if (flag) {
                initPurtiMapper.delete(new QueryWrapper<InitPurti>()
                        .eq("TI001", initThdDto.getTI001())
                        .eq("TI002", dh));
                for (InitPurtj purtj : list) {
                    initPurtjMapper.delete(new QueryWrapper<InitPurtj>()
                            .eq("TJ001", purtj.getTj001())
                            .eq("TJ002", dh)
                            .eq("TJ003", purtj.getTj003()));
                }
            }
            return Result.fail("出现异常请查看审批后台是否开启");
        }
        return Result.ok("单据生成成功:" + initThdDto.getTI001() + '_' + dh);
    }


    @Override
    public Result saveTransferSlip(StockTrading stockTrading) throws UnknownHostException {
        DynamicDataSourceContextHolder.push(stockTrading.getCompany());
        boolean flag = false;
        Invta invta = new Invta();
        String dh = "";
        Integer count = invtaMapper.selectCount(new QueryWrapper<Invta>()
                .eq("TA001", stockTrading.getTA001())
                .eq("TA002", stockTrading.getTA002())
                .eq("TA006", "Y"));
        if (count >= 1) {
            return Result.fail().message("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据");
        }
        Dscmb dscmb = dscmbMapper.selectOne(new QueryWrapper<Dscmb>().eq("MB003", stockTrading.getCompany()));
        String company = dscmb.getMB001().trim();
        Integer count1 = invtaMapper.selectCount(new QueryWrapper<Invta>()
                .eq("TA001", stockTrading.getTA001())
                .eq("TA002", stockTrading.getTA002())
                .eq("TA006", "N"));
        if (count1 >= 1) {
            dh = stockTrading.getTA002();
            invtaMapper.delete(new QueryWrapper<Invta>()
                    .eq("TA001", stockTrading.getTA001())
                    .eq("TA002", stockTrading.getTA002()));
            invtbMapper.delete(new QueryWrapper<Invtb>()
                    .eq("TB001", stockTrading.getTA001())
                    .eq("TB002", stockTrading.getTA002()));
        } else {
            Integer count2 = invtaMapper.selectCount(new QueryWrapper<Invta>()
                    .eq("UDF12", stockTrading.getTA002()));
            if (count2 >= 1) {
                return Result.fail().message("此单号已存在");
            } else {
                flag = true;
                dh = commonService.getIdByType(stockTrading.getTA001(), "INVTA");
                invta.setUdf12(stockTrading.getTA002());
            }
        }
        Double sum = 0.0;
        Double sumPrice = 0.00;
        List<Invtb> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();

        //TODO 公司名称暂时写死
        invta.setCompany(company);
        invta.setCreator("MES");
        invta.setUsrGroup(commonMapper.getUsrGroup("MES"));
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyyMM");
        DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter create_date = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

        invta.setCreateDate(currentTime.format(create_date));
        invta.setFlag(1.0);
        invta.setTa001(stockTrading.getTA001());
        invta.setTa002(dh);
        invta.setTa003(stockTrading.getTA003());
        invta.setTa006(stockTrading.getTA006());
        invta.setTa007(0.0);
        //TODO 工厂编号先写死
        invta.setTa008(stockTrading.getTA008());
        invta.setTa009(stockTrading.getTA009());
        invta.setTa010(0.0);
        for (StockTradingBody stockTradingBody : stockTrading.getStockTradingBodies()) {
            Invtb invtb = new Invtb();
            invtb.setCompany(company);
            invtb.setCreator("MES");
            invtb.setUsrGroup(commonMapper.getUsrGroup("MES"));
            invtb.setCreateDate(currentTime.format(create_date));
            invtb.setFlag(1.0);
            invtb.setTb001(stockTradingBody.getTB001());
            invtb.setTb002(dh);
            invtb.setTb003(stockTradingBody.getTB003());
            Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().eq("MB001", stockTradingBody.getTB004()));
            if (invmb == null) {
                return Result.fail().message("此品号不存在");
            }
            invtb.setTb004(stockTradingBody.getTB004());
            invtb.setTb005(invmb.getMb002());
            invtb.setTb006(invmb.getMb003());
            invtb.setTb007(stockTradingBody.getTB007());
            sum += stockTradingBody.getTB007();
            invtb.setTb008(stockTradingBody.getTB008());
            invtb.setTb009(stockTradingBody.getTB007());
            //TODO 单位成本不知道在哪
            invtb.setTb010(0.0);
            //TODO 易飞金额都是0.00
            invtb.setTb011(0.00);
            invtb.setTb012(stockTradingBody.getTB012());
            invtb.setTb013(stockTradingBody.getTB013());
            invtb.setTb014("********************");
            invtb.setTb029("##########");
            invtb.setTb030("##########");
            invtb.setTb018(stockTradingBody.getTB018());
            invtb.setTb021("********************");
            invtb.setTb022(0.000000);
            invtb.setTb025(0.000000);
            invtb.setTb026(0.000000);
            invtb.setTb027(0.000000);
            invtb.setTb035(0.000000);
            invtb.setTb036(0.000000);
            invtb.setTb037(0.000000);
            list.add(invtb);
        }
        invta.setTa011(sum);
        invta.setTa012(sumPrice);
        invta.setTa013("N");
        invta.setTa014(currentTime.format(yyyyMMdd));
        invta.setTa015("MES");
        invta.setTa016(0.000000);
        invta.setTa017("N");
        invta.setTa021(0.0);
        invta.setTa025("1");
        invta.setTa029(0.000000);
        invta.setTa030(0.000000);
        invta.setTa031(0.000000);
        invta.setTa033("********************");
        invta.setUdf51(0.000000);
        invta.setUdf52(0.000000);
        invta.setUdf53(0.000000);
        invta.setUdf54(0.000000);
        invta.setUdf55(0.000000);
        invta.setUdf56(0.000000);
        invta.setUdf57(0.000000);
        invta.setUdf58(0.000000);
        invta.setUdf59(0.000000);
        invta.setUdf60(0.000000);
        invta.setUdf61(0.000000);
        invta.setUdf62(0.000000);
        invtaMapper.insert(invta);
        for (Invtb invtb : list) {
            invtbMapper.insert(invtb);
        }

        Integer i = invtbMapper.selectCount(new QueryWrapper<Invtb>()
                .eq("TB001", stockTrading.getTA001())
                .eq("TB002", dh));
        if (i == null || i <= 0) {
            invtaMapper.delete(new QueryWrapper<Invta>()
                    .eq("TA001", stockTrading.getTA001())
                    .eq("TA002", dh));
            return Result.fail().message("单身生成失败");
        }

        ShenHe shenHe = new ShenHe();
        shenHe.setCom(company);
        shenHe.setProgram("INVI08");
        shenHe.setUser("MES");
        shenHe.setDb(stockTrading.getTA001());
        shenHe.setDh(dh);
        shenHe.setType("DO");
        shenHe.setRq(currentTime.format(yyyyMMdd));

        InetAddress localhost = InetAddress.getLocalHost();
//        String ipAddress = localhost.getHostAddress();
        String ipAddress = "192.168.1.192";
        String url = "http://" + ipAddress + ":9000/api/yifei/audit";

        String jsonString = JSON.toJSONString(shenHe);
        String ans = null;
        try {
            ans = HttpClientUtil.postRequest(url, jsonString);
            HttpResult httpResult = JSON.parseObject(ans, HttpResult.class);
            if (httpResult.getStatus().equals("失败")) {
                if (flag) {
                    enterStorageMapper.deleteINVTA(invta);
                    for (Invtb invtb : list) {
                        enterStorageMapper.deleteINVTB(invtb);
                    }
                }
                return Result.fail().message(httpResult.getReason() + httpResult.getDetail());
            }
        } catch (Exception e) {
            System.out.println("出现异常请查看审批后台是否开启");
            if (flag) {
                enterStorageMapper.deleteINVTA(invta);
                for (Invtb invtb : list) {
                    enterStorageMapper.deleteINVTB(invtb);
                }
            }
            return Result.fail().message("出现异常请查看审批后台是否开启");
        }
        return Result.ok("单据生成成功:" + stockTrading.getTA001() + '_' + dh);
    }

    @Override
    public List<NeedArrivalInsVo> needArrivalInsCustomer() {
        return enterStorageMapper.needArrivalInsCustomer();
    }

    /**
     * 根据库位插入信息
     */
    private boolean insertByTh072(LocalDateTime now, String formattedDateTime, InitPURTHDto purth, List<WmsInvml> invmlList, List<WmsInvla> wmsInvlas) {
        String db = purth.getTH001();
        String creator = purth.getCreator();
        String userGroup = purth.getUsrGroup();
        String company = purth.getCompany();
        WmsInvla wmsInvla1 = wmsInvlaMapper.selectOne(new QueryWrapper<WmsInvla>()
                .eq("LA005", -1.0)
                .eq("LA006", purth.getTH001())//单别
                .eq("LA007", purth.getTH002())//单号
                .eq("LA008", purth.getTH003())//序号
                .eq("LA023", purth.getTH072())//库位
                .eq("LA009",purth.getTH009())//仓库
                .eq("LA016",purth.getTH010()));//批号

        if (wmsInvla1 != null) {
            Double t= wmsInvla1.getLa011()+purth.getTH015() ;
            wmsInvla1.setLa011(t);//把交易明细信息档里的库存量叠加

            int i=wmsInvlaMapper.update(wmsInvla1,new QueryWrapper<WmsInvla>()
                    .eq("LA005",1.0)
                    .eq("LA006", purth.getTH001())//单别
                    .eq("LA007", purth.getTH002())//单号
                    .eq("LA008", purth.getTH003())//序号
                    .eq("LA023", purth.getTH072())//库位
                    .eq("LA009",purth.getTH009())//仓库
                    .eq("LA016",purth.getTH010()));//批号
            if (i!=1){
                return false;
            }

        }
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = now.format(formatter1);
        WmsInvml wmsInvml = new WmsInvml();
        WmsInvla wmsInvla = new WmsInvla();
        wmsInvml = wmsInvmlMapper.selectOne(new QueryWrapper<WmsInvml>()
                .eq("ML001", purth.getTH004())//品号
                .eq("ML002", purth.getTH009())//仓库
                .eq("ML003", purth.getTH072())//库位
                .eq("ML004", purth.getTH010()));//批号
        if (wmsInvml == null) {
            wmsInvml = new WmsInvml();
            String uuid = UUID.randomUUID().toString();
            wmsInvml.setUdf12(uuid);
            wmsInvml.setCompany(company);
            wmsInvml.setCreator(creator);
            wmsInvml.setUsrGroup(userGroup);
            wmsInvml.setCreateDate(formattedDateTime);
//                wmsInvml.setModifier(mocte.getModifier());
//                wmsInvml.setModiDate(mocte.getModiDate());
            wmsInvml.setFlag(1.0);
            wmsInvml.setMl001(purth.getTH004());//品号
            wmsInvml.setMl002(purth.getTH009());//仓库
            wmsInvml.setMl003(purth.getTH072());//库位
            wmsInvml.setMl004(purth.getTH010());//批号
            wmsInvml.setMl005(0-purth.getTH015());//库存数量
            wmsInvml.setMl006(0-purth.getTH015());//库存包装数量
            wmsInvml.setMl009(formattedDate);//最近入库日
            int i = wmsInvmlMapper.insert(wmsInvml);
            if (i != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        } else {
            invmlList.add(wmsInvml);

            Double t = wmsInvml.getMl005() + purth.getTH015();
            wmsInvml.setMl005(t);

            int i = wmsInvmlMapper.update(wmsInvml, new QueryWrapper<WmsInvml>()
                    .eq("ML001", wmsInvml.getMl001())//品号
                    .eq("ML002", wmsInvml.getMl002())//仓库
                    .eq("ML003", wmsInvml.getMl003())//库位
                    .eq("ML004", wmsInvml.getMl004()));//批号
            if (i != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        wmsInvla.setCompany(company);
        wmsInvla.setCreator(creator);
        wmsInvla.setUsrGroup(userGroup);
        wmsInvla.setCreateDate(formattedDateTime);
//            wmsInvla.setModifier(mocte.getModifier());
//            wmsInvla.setModiDate(mocte.getModiDate());
        wmsInvla.setFlag(1.0);
        wmsInvla.setLa001(purth.getTH004());//品号
        wmsInvla.setLa004(formattedDate);//日期
//            这四位不能重复
        wmsInvla.setLa005(1.0);//按单据性质的库存影响:减 或 调拨单性质的出写入为-1，其余为+1。
        wmsInvla.setLa006(purth.getTH001());//单别
        wmsInvla.setLa007(purth.getTH002());//单号
        wmsInvla.setLa008(purth.getTH003());//序号
        wmsInvla.setLa009(purth.getTH009());//仓库
        wmsInvla.setLa010(purth.getTH033());//备注
        wmsInvla.setLa011(purth.getTH015());//单据交易库存数量
        wmsInvla.setLa012(0.0);
        wmsInvla.setLa013(0.0);
        wmsInvla.setLa014("1");
        wmsInvla.setLa015("");
        wmsInvla.setLa016(purth.getTH010());//批号
        wmsInvla.setLa017(0.0);
        wmsInvla.setLa018(0.0);
        wmsInvla.setLa019(0.0);
        wmsInvla.setLa020(0.0);
        wmsInvla.setLa021(0.0);
        wmsInvla.setLa022(formattedDate);//审核时间
        wmsInvla.setLa023(purth.getTH072());//库位
        wmsInvla.setLa024("");
        wmsInvlas.add(wmsInvla);
        wmsInvlaMapper.insert(wmsInvla);
        return true;
    }
}
